package org.example.ai_chat.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.ai_chat.util.JsonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

@Component
public class LoginvalidateInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(LoginvalidateInterceptor.class.getName());
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!StpUtil.isLogin()) {
            response.setHeader("Content-Type","application/json;charset=utf-8");
            PrintWriter out = response.getWriter();

            JsonResponse jsonResponse = new JsonResponse();
            jsonResponse.setCode(1);
            jsonResponse.setMsg("您还未登录，请先登录");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(jsonResponse);
            out.println(json);
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.debug("拦截器的postHandle方法被调用");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.debug("拦截器的afterCompletion方法被调用");
    }
}
